<?php

namespace frontend\models;

use Yii;
use backend\models\Goods;

/**
 * This is the model class for table "cart".
 *
 * @property integer $id
 * @property string $goods_id
 * @property string $amount
 * @property string $member_id
 */
class Cart extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cart';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['goods_id', 'amount', 'member_id'], 'required'],
            [['goods_id', 'amount', 'member_id'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'goods_id' => '商品',
            'amount' => '商品数量',
            'member_id' => '会员id',
        ];
    }
    /** 同不cookie中的购物车中的数据到数据表中 */
    public static function synCartCookie(){
        $member_id = Yii::$app->user->id;
        //读取请求中的cookies中的购物车中的信息
        $data = \Yii::$app->request->cookies->get('cart');
        if(!empty($data)){
            $data = unserialize($data);
            foreach($data as $goods_id=>$amount){
                //$cartobj = new Cart();
                //$cartobj->amount = $amount;
                //$cartobj->goods_id = $goods_id;
                //$cartobj->member_id =$member_id;
                //$cartobj->validate();
                //$cartobj->save();
                self::AddCart($goods_id,$amount);
            }
            //保存成功后删除cookie中的购物车
            Yii::$app->response->cookies->remove('cart');
        }
    }

    public static function AddCart($goods_id,$amount){
            $member_id = \Yii::$app->user->id;
            //判断当前商品在购物车中是否存在
            if($cart = Cart::findOne(['goods_id'=>$goods_id,'member_id'=>$member_id])){
                $cart->amount+=$amount;
            }else{
                $cart = new Cart();
                $cart->member_id = $member_id;
                $cart->amount = $amount;
                $cart->goods_id = $goods_id;
            }
            return $cart;
    }


	public function getGoods(){
		return $this->hasOne(Goods::classname(),['id'=>'goods_id']);
	}
	
	
}
